package com.dzsw.zk;

import org.apache.commons.lang.math.NumberUtils;
import org.apache.zookeeper.*;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.CountDownLatch;

@SpringBootApplication(scanBasePackages = {
        "com.dzsw.zk"
})
public class ZkDemoApp {

    public static void main(String[] args) throws UnknownHostException {
        SpringApplication.run(ZkDemoApp.class);
//        getLocalIp();
//        test1();
//        test2();
    }

    public static void test1() {
        ZooKeeper zooKeeper = null;
        try {
            final CountDownLatch countDownLatch = new CountDownLatch(1);
            //连接成功后，会回调watcher监听，此连接操作是异步的，执行完new语句后，直接调用后续代码
            //  可指定多台服务地址 127.0.0.1:2181,127.0.0.1:2182,127.0.0.1:2183
            String connectString = "192.168.1.25:2181,192.168.1.25:2182,192.168.1.25:2183";
            int timeout = 4000;
            zooKeeper = new ZooKeeper(connectString, timeout, new Watcher() {
                @Override
                public void process(WatchedEvent event) {
                    if (Event.KeeperState.SyncConnected == event.getState()) {
                        //如果收到了服务端的响应事件,连接成功
                        countDownLatch.countDown();
                    }
                }
            });
            countDownLatch.await();
            System.out.println(String.format("【初始化ZooKeeper连接状态....】=%s", zooKeeper.getState()));

            for (int i = 0; i < 1024; i++) {
                String s = zooKeeper.create("/zookeeper/" + i, getLocalIp().getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
                System.out.println(s);
                String strWnId = s.replace("/zookeeper/", "");
                Integer wnId = Integer.valueOf(strWnId);
                System.out.println(String.format("SRC=[%s], INT=[%s], [%s]->[%s]", strWnId ,wnId, wnId >> 5, wnId & 0b11111));
            }
            System.out.println("===============================================================");
            List<String> list = zooKeeper.getChildren("/zookeeper", false);
            list.sort((o1, o2)->{
                if (NumberUtils.isNumber(o1) && NumberUtils.isNumber(o2)) {
                    return Integer.parseInt(o1) - Integer.valueOf(o2);
                }
                return 0;
            });

            for (int i = 0; i < list.size(); i++) {
                System.out.println(list.get(i));
            }
            Thread.sleep(60 * 1000);
        } catch (Exception e) {
            System.out.println(String.format("初始化ZooKeeper连接异常....】=%s", e));
        }
    }

    public static void test2() {
        ZooKeeper zooKeeper = null;
        try {
            final CountDownLatch countDownLatch = new CountDownLatch(1);
            //连接成功后，会回调watcher监听，此连接操作是异步的，执行完new语句后，直接调用后续代码
            //  可指定多台服务地址 127.0.0.1:2181,127.0.0.1:2182,127.0.0.1:2183
            String connectString = "192.168.85.191:2181";
            int timeout = 4000;
            zooKeeper = new ZooKeeper(connectString, timeout, new Watcher() {
                @Override
                public void process(WatchedEvent event) {
                    if (Event.KeeperState.SyncConnected == event.getState()) {
                        //如果收到了服务端的响应事件,连接成功
                        countDownLatch.countDown();
                    }
                }
            });
            countDownLatch.await();
            System.out.println(String.format("【初始化ZooKeeper连接状态....】=%s", zooKeeper.getState()));
            String s = zooKeeper.create("/zookeeper/1", getLocalIp().getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
            System.out.println(s);
            s = zooKeeper.create("/zookeeper/1", getLocalIp().getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
            System.out.println(s);
            Thread.sleep(60 * 1000);
        } catch (Exception e) {
            System.out.println(String.format("初始化ZooKeeper连接异常....】=%s", e));
        } finally {
            try {
                if (zooKeeper != null) {
                    zooKeeper.close();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static String getLocalIp() throws UnknownHostException {
        InetAddress addr = InetAddress.getLocalHost();
        String ip = addr.getHostAddress();
        System.out.println(ip);
        return ip;
    }
}
